package com.woniu.inInterceptor;

import com.alibaba.fastjson.JSON;
import com.woniu.util.JWTUtil;
import com.woniu.util.ResponseData;
import com.woniu.util.ResponseEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 1实现HandlerInterceptor
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 实现步骤
     * 1先获取前端jwt（前端的jwt会存在请求头中）
     * 2用系统的密钥解密
     * 3拿前端的jwt和redis的做对比
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //1获取前端jwt（从请求头中获取jwt）
        String handlerJWT = request.getHeader("token");
        String jsonString = JSON.toJSONString(ResponseData.fail(ResponseEnum.NO_LOGIN));
        if (handlerJWT == null){
            //拦截
            //给前端响应 json工具类
            //把Java对象转换成json字符串
//            String jsonString = JSON.toJSONString(ResponseData.fail(ResponseEnum.NO_LOGIN));
            //转成JSON字符串，前端才能认识，才能res.data
            response.getWriter().print(jsonString);
            return false;
        }
        if (!JWTUtil.verifyJWT(handlerJWT)){
            response.getWriter().print(jsonString);
            return false;
        }
        //2用系统密钥解密jwt
        Integer useId = JWTUtil.getUseId(handlerJWT);
        String redisJWT = redisTemplate.opsForValue().get("JWT:" + useId);
        if (!handlerJWT.equals(redisJWT)){
            response.getWriter().print(jsonString);
            return false;
        }
        //给
        redisTemplate.expire("JWT:" + useId,20, TimeUnit.DAYS);//给指定的key重新设置TTL时间

//        return HandlerInterceptor.super.preHandle(request,response,handlerJWT)   ;
        return true  ;
    }


}
